﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using UrlRouter.Configuration;

namespace UrlRouter.Web
{
    public class ReverseRoute
    {
        /// <summary>
        /// 匹配转换成虚拟url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetUrl(string url)
        {
                        

            foreach (ReverseRouteModel rrm in GetUrlsList())
            {
                Regex re = new Regex(rrm.VirtualPath, RegexOptions.IgnoreCase);
                if (re.IsMatch(url))
                {



                    return re.Replace(url, rrm.ToUrl, 1);

                }
                //else
                //{
                //    string vvv = rrm.VirtualPath;
                //}

            }
            return url;
        
        
        }
        /// <summary>
        /// 输入正规则，输出反置的规则实体
        /// </summary>
        /// <param name="route"></param>
        /// <returns></returns>
        public static ReverseRouteModel Get(ReverseRouteModel route)
        {
            ReverseRouteModel result = new ReverseRouteModel();

            string New_toUrl = route.VirtualPath; //反转定义
            string New_virtualUrl = Regex.Escape(route.ToUrl);

            List<string> virtualList = new List<string>();

            MatchCollection virtualMatch = Regex.Matches(route.VirtualPath, @"(\(.+?\))");

            //先遍历出来转存到List ,List输出内容后倒置成位置索引
            foreach (Match m in virtualMatch)
            {
                virtualList.Add(m.Groups[1].Value);
            }

            Regex tourlReg = new Regex(@"\$(\d+)");

            int i = 1;
            foreach (Match m in tourlReg.Matches(route.ToUrl))
            {
                int GroupNum = Convert.ToInt32(m.Groups[1].Value);
                if (virtualList.Count >= GroupNum)
                {
                    New_virtualUrl = New_virtualUrl.Replace("\\" + m.Value, string.Format("{0}", virtualList[GroupNum - 1]));
                    virtualList[GroupNum - 1] = "$" + i.ToString(); //将虚拟Url的索引位置倒置进去 也就是当前索引
                    i++;
                }

            }
            int k = 0;
            foreach (Match matGroup in virtualMatch)
            {
                //这里的遍历和预存virtualList是一样的,为了能够对应索引位置
                //替换相同索引位置的规则匹配组为新的虚拟匹配组位置索引,已经基本支持更复杂的规则匹配
                Regex re = new Regex(Regex.Escape(matGroup.Value));
                New_toUrl = re.Replace(New_toUrl, virtualList[k], 1);
                k++;
            }
            result.ToUrl = New_toUrl.Replace("\\", "");
            result.VirtualPath = New_virtualUrl; //这里还要解决字符转义问题
            return result;
            

        }

        
        /// <summary>
        /// 反转成功的urls集合 [实体LIST泛型]
        /// </summary>
        /// <returns></returns>
        public static List<ReverseRouteModel> GetUrlsList()
        {
            string cacheName = "Rewriting_ReverseRoute_Rule_Urls";

            List<ReverseRouteModel> ListUrls = null;
            UrlHelper urlhelper = new UrlHelper();

            ListUrls = System.Web.HttpContext.Current.Cache[cacheName] as List<ReverseRouteModel>;

            if (ListUrls == null)
            {
                ListUrls = new List<ReverseRouteModel>();

                foreach (RewriteSettings rewriteSettings in UrlRewriting.Configuration.Rewrites)
                {
                    ReverseRouteModel rrm = new ReverseRouteModel();
                    rrm.VirtualPath = rewriteSettings.GetAttribute("virtualUrl", "");
                    rrm.ToUrl = rewriteSettings.GetAttribute("toUrl", "");

                    rrm = Get(rrm);
                    rrm.ToUrl = urlhelper.RemoveHandleRoot(rrm.ToUrl);
                    rrm.VirtualPath = urlhelper.HandleRootOperator(rrm.VirtualPath);

                    ListUrls.Add(rrm);

                }

                System.Web.HttpContext.Current.Cache[cacheName] = ListUrls;
            }

            return ListUrls;

      
        }

       
        



    }
    /// <summary>
    /// 反转实体
    /// </summary>
    public class ReverseRouteModel
    {
        /// <summary>
        /// 虚拟url
        /// </summary>
        public string VirtualPath { get; set; }
        /// <summary>
        /// 实际url
        /// </summary>
        public string ToUrl { get; set; }
    }

}
